package com.dsmbase.corp.user.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;

import com.dsmbase.corp.user.domain.User;

@Component
public class UserDao {

	private JdbcTemplate jdbcTemplate;
	@Autowired
	private DataSource dataSource;

	private static final String INSERT_SQL = "insert into user values(null,?,?)";
	private static final String SELECT_BY_ID_SQL = "select id, user_name, user_password from user where id = ?";
	private static final String SELECT_BY_NAME_SQL = "select id, user_name, user_password from user where user_name = ?";
	private static final String SELECT_ALL_USER_SQL = "select * from user"; 

	@Autowired
	public void setDataSource(DataSource ds) {
		dataSource = ds;
		this.jdbcTemplate = new JdbcTemplate(dataSource);
	}

	public void addUser(User user) throws SQLException {
		Object[] params = new Object[] { user.getUserName(),
				user.getUserPassword() };
		int[] argTypes = new int[] { Types.VARCHAR, Types.VARCHAR };
		jdbcTemplate.update(INSERT_SQL, params, argTypes);
	}

	public User getUserById(int id) throws SQLException {
		Object[] params = new Object[] { id };
		User user = (User) jdbcTemplate.queryForObject(SELECT_BY_ID_SQL,
				params, new UserRowMapper());
		return user;
	}

	public User getUserByName(String userName) throws SQLException {
		Object[] params = new Object[] { userName };
		User user = (User) jdbcTemplate.queryForObject(SELECT_BY_NAME_SQL,
				params, new UserRowMapper());
		return user;
	}
	
	public List<User> getAllUser() throws SQLException {
		List<User> list = jdbcTemplate.query(SELECT_ALL_USER_SQL, new SecurityUserRowMapper());
		return list;
	}
	
	public class UserRowMapper implements RowMapper<User> {

		public User mapRow(ResultSet rs, int index) throws SQLException {
			User user = new User(rs.getInt("id"), rs.getString("user_name"),
					rs.getString("user_password"));
			return user;
		}

	}
	
	public class SecurityUserRowMapper implements RowMapper<User> {

		public User mapRow(ResultSet rs, int index) throws SQLException {
			User user = new User(rs.getInt("id"), rs.getString("user_name"));
			return user;
		}

	}


}
